package store

import (
	"context"
	baseLog "gitee.com/zaiqiang231/go-base-app/base_app/log"
	"gitee.com/zaiqiang231/lovesport-authz-service/app/config"
	"gitee.com/zaiqiang231/lovesport-authz-service/app/constant"
	"github.com/go-redis/redis/v8"
	"sync"
	"time"
)

var (
	redisStore     redis.UniversalClient
	onceRedisStore sync.Once
)

func InitRedisStore(opts *config.RedisConfig) (redis.UniversalClient, error) {
	if opts == nil {
		baseLog.Errorf("InitRedisStore opts err : ", opts)
	}
	onceRedisStore.Do(func() {
		redisStore = redis.NewClient(&redis.Options{
			Addr:     opts.Addr,
			Password: opts.Password, // no password set
			DB:       0,             // use default DB
		})
	})

	if redisStore == nil {
		return nil, constant.ErrFailedGetStore
	}
	return redisStore, nil
}

func GetRedisStore() redis.UniversalClient {
	if redisStore == nil {
		baseLog.Errorf("GetRedisStore redis instance is %v", redisStore)
	}
	return redisStore
}

func AppendToSetPipelined(key string, values [][]byte, timeout time.Duration) {
	if redisStore == nil {
		baseLog.Errorf("AppendToSetPipelined redis instance is %v", redisStore)
	}

	pipe := redisStore.Pipeline()
	for _, val := range values {
		pipe.RPush(context.Background(), key, val)
	}

	if _, err := pipe.Exec(context.Background()); err != nil {
		baseLog.Errorf("Error trying to append to set keys: %s", err.Error())
	}

	if timeout > -1 {
		redisStore.Expire(context.Background(), key, timeout)
	}

}
